<template>
  <div class="basicForm">
    <editForm :formConfig="basicConfig" ref="basicForm" :formData="formData">
      <template #source="{ editFormInfo, item }">
        <div class="dayInput">
          <el-select
            style="flex: 1"
            size="mini"
            v-model="editFormInfo.source"
            :title="getSelectTitle(item.selectOption, editFormInfo.source)"
            placeholder="请选择"
            :disabled="item.disabled"
            @change="item.methods"
          >
            <el-option
              v-for="(option, i) in item.selectOption"
              :key="i"
              :label="option.label"
              :value="option.value"
            >
            </el-option>
          </el-select>
          <el-button
            v-if="createByRobot && pageType != 'add'"
            icon="el-icon-link"
            size="mini"
            class="link"
            plain
            @click="goToPatrolRobot(editFormInfo.id)"
            >巡检</el-button
          >
          <el-button
            v-if="showPatrol"
            size="mini"
            class="link"
            plain
            @click="selectPatrol()"
            >关联巡视单</el-button
          >
        </div>
      </template>
    </editForm>
    <div class="attachConten">
      <div class="attachTitle">
        <span class="redPoint" v-if="!createByRobot">* </span
        >现场照片:
      </div>
      <div class="tebleDiv">
        <attachFormNew
          style="width: 60%"
          :disabled="baseAttachBtn"
          @uploadSuccess="uploadSuccess"
          :attachSetting="attachSetting"
          :isListView="false"
          isDelete
          multiple
          ref="attachFile"
        ></attachFormNew>
      </div>
    </div>
    <dialogPublic
      :title="'选择缺陷关键字'"
      :show.sync="showKeyword"
      @doSubmit="selectKeys"
      @doClose="() => (showKeyword = false)"
      appendTobody
      fullscreen
    >
      <keyword ref="defectKeys"></keyword>
    </dialogPublic>
  </div>
</template>

<script>
import {
  getDetailsApi, //获取缺陷工单详情
} from "@/api/orderManagement/defectOrder";
import { getEquipment } from "@/api/equipmentLedger/equipmentManage";
import {
  getPresetParamsApi, //获取设备参数
} from "@/api/common";
import keyword from "@/views/standardManagement/defectLibrary/defectRelatePage"; //缺陷关键字

export default {
  props: {
    initData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    orderStatus: {
      type: String,
      default: "",
    },
    pageType: {
      type: String,
      default: "",
    },
    oldMajor: {
      type: String,
      default: null,
    },
    createByRobot: {
      type: Boolean,
      default: false,
    },
  },
  components: { keyword },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      showKeyword: false,
      status: "",
      currentEquipmentName: "",
      currentOrg: "",
      currentEquipment: "",
      currentKeys: "",
      formData: {},
      source:"",
      basicConfig: {
        itemArr: [
          {
            label: "设备名称",
            prop: "equipmentName", //多选时，字段要为数组类型
            propArr: "equipmentArr",
            idsStr: "equipmentId",
            filterConfig: ["hasManagerUnit"],
            //过滤条件：hasManagerUnit:该设备是否关联单位，filterManagerUnit:筛选指定单位的设备,filterStandard:关联了标准的设备
            managerUnit: [], //指定过滤的设备管理单位id filterConfig包含filterManagerUnit的时候使用
            // standardType: "maintain",
            //标准类型 正常维护：maintain,大修：overhaul,检修：repair,试验：experiment，巡视：patrol
            multiple: false, //是否多选
            allowCreate: false, //是否允许创建条目
            option: [], //this.deptOption
            type: "device-select", //类型
            trigger: "change",
            required: true,
            methods: (obj) => {
              let { name, id, typeId } = obj[0];
              //带出专业
              this.currentEquipmentName = name;
              this.currentEquipment = id;
              let form = { equipmentId: id, typeId };
              if (JSON.stringify(obj[0]) == "{}") {
                this.currentOrg = "";
                this.$refs.basicForm.setFormItem("deptManageName", "");
                this.$refs.basicForm.setFormItem("deptManage", "");
                this.$refs.basicForm.setFormItem("major", "");
              } else {
                this.setDeptManage(form);
              }
            },
            rows: 2,
            span: 6,
            moreBtn: true,
            moreBtnMethod: (form) => {
              if (form.equipmentId) {
                this.goDetailPage(form);
              } else {
                this.$message.warning("请先选择设备！");
              }
            },
          },
          {
            label: "设备管理单位",
            prop: "deptManageName",
            idsStr: "deptManage",
            type: "text",
            placeholder: "选择设备后带出",
            required: true,
            disabled: true,
            span: 6,
          },
          {
            label: "生产厂家",
            prop: "manufacturer",
            type: "text",
            placeholder: "选择设备后带出",
            required: false,
            disabled: true,
            span: 6,
          },
          {
            label: "型号规格",
            prop: "model",
            type: "text",
            placeholder: "选择设备后带出",
            required: false,
            disabled: true,
            span: 6,
          },
          {
            type: "select",
            label: "所属类别",
            prop: "type",
            required: true,
            selectOption: this.$store.getters["dirtData"]("order_defect_type"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "order_defect_type",
                val
              );
            },
            disabled: false,
            span: 6,
          },
          {
            type: "select",
            label: "专业",
            prop: "major",
            required: true,
            selectOption: this.$store.getters["dirtData"]("common_major"),
            formatter: (val) => {
              return this.$store.getters["fineDirtDataName"](
                "common_major",
                val
              );
            },
            span: 6,
          },
          {
            label: "发现人",
            prop: "finderName", //多选时，字段要为数组类型
            propArr: "finderNameArr",
            idsStr: "finder",
            multiple: false, //是否多选
            isOutOrg: 0, //是否是外单位
            allowCreate: true, //是否允许创建条目
            option: [], //当前选中的项
            type: "user-select", //类型
            trigger: "change",
            methods: (obj) => {},
            span: 6,
          },
          {
            label: "发现时间",
            prop: "findTime",
            type: "datetime",
            required: true,
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              },
            },
            span: 6,
          },
          {
            label: "缺陷关键字",
            prop: "keys", //多选时，字段要为数组类型
            //propArr: "keyArr",
            idsStr: "keysId",
            //option: [],
            type: "defectKeyWord", //类型
            trigger: "change",
            methods: (obj) => {
              this.selectKeys(obj);
            },
            required: true,
            span: 6,
          },
          {
            type: "select",
            label: "缺陷等级",
            prop: "level",
            trigger: "change",
            required: true,
            selectOption: this.$store.getters["dirtData"]("defect_order_level"),
            methods: (val) => {
              // this.changeType = val.value;
            },
            span: 6,
          },
          {
            type: "select",
            label: "工单来源",
            prop: "source",
            required: true,
            selectOption: this.$store.getters["dirtData"](
              "order_defect_source"
            ),
            span: 6,
            methods:(val)=>{
              this.source = val;
            }
          },
          {
            label: "应完成处理时间",
            prop: "expectEndTime",
            type: "datetime",
            isHide: true,
            span: 6,
          },
          // {
          //   label: "占位格",
          //   prop: "",
          //   otherInfo: "table",
          //   span: 12,
          // },
          {
            label: "缺陷描述",
            prop: "desc",
            type: "textarea",
            maxlength: "100",
            required: true,
            span: 12,
            rows: 3,
          },
          {
            label: "预采取措施",
            prop: "measure",
            type: "textarea",
            maxlength: "100",
            required: true,
            span: 12,
            rows: 3,
          },
          {
            label: "消缺建议",
            prop: "suggestion",
            type: "textarea",
            maxlength: "100",
            span: 12,
            rows: 3,
          },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            maxlength: "100",
            span: 12,
            rows: 3,
          },
        ],
      },
      //附件设置
      attachSetting: {
        businessId: "", //单据的ID
        businessType: "base",
      },
    };
  },
  computed: {
    baseAttachBtn() {
      if (
        (["DRAFT", ""].includes(this.status) && this.pageType != "detail") ||
        this.reviewCanEdit
      ) {
        return false;
      } else {
        return true;
      }
    },
    defaultTitle() {
      return this.currentOrg + this.currentEquipmentName + this.currentKeys;
    },
    reviewCanEdit() {
      let { currNodeName, currNodeUser, status } = this.formData;
      if (currNodeUser) {
        let userArr = currNodeUser.split(",");
        return (
          currNodeName == "设备管理单位领导审核" &&
          userArr.includes(this.userInfo.name) &&
          status == "WAIT_REVIEW"
        );
      } else {
        return false;
      }
    },
    showPatrol(){
      return this.status=='DRAFT' && this.source=='tour';
    }
  },
  watch: {
    defaultTitle: {
      handler(val) {
        this.orderTitle = val;
        this.$emit("setOrderTitle", val);
      },
    },
    orderStatus: {
      handler(val) {
        this.status = val;
        if (val == "WAIT_REVIEW") {
          let { currNodeName, currNodeUser, currNodeUserId } = this.formData;
        }
      },
    },
    pageType: {
      handler(val) {
        if (val != "add") {
          this.initForm();
        } else {
          this.init();
        }
      },
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.formData = this.initData;
      if (this.pageType == "add") {
        //新增
        //初始化发现人
        let { name, id, isOutOrg } = this.userInfo;
        this.userOption = this.$utils.getOptionData(name, id, isOutOrg);
        //设置发现人的Option
        this.$nextTick(() => {
          this.$refs.basicForm.setItemOption("finderName", this.userOption);
        });
      }
    },
    initForm() {
      let itemArr = [];
      $.extend(true, itemArr, this.basicConfig.itemArr);
      itemArr.map((i) => {
        if (this.status != "DRAFT") {
          i.disabled = true;
        } else if (
          !["deptManageName", "type", "model", "manufacturer"].includes(i.prop)
        ) {
          i.disabled = false;
        }

        if (i.prop == "expectEndTime") {
          if (["DRAFT", "", "WAIT_REVIEW"].includes(this.status)) {
            i.isHide = true;
          } else {
            i.isHide = false;
          }
        }
      });
      if (["query", "detail"].includes(this.pageType)) {
        itemArr.map((i) => (i.disabled = true));
      }
      if (this.reviewCanEdit) {
        itemArr.map((i) => {
          if (
            !["deptManageName", "type", "model", "manufacturer"].includes(
              i.prop
            )
          ) {
            i.disabled = false;
          }
        });
      }
      this.basicConfig.itemArr = itemArr;
    },
    getSelectTitle(option, value) {
      let one = option.find((item) => item.value == value) || {};
      return one.label;
    },
    //获取缺陷工单基本信息
    getDetails(id) {
      let dataId = id ? id : this.formData.id;
      getDetailsApi(dataId).then((res) => {
        let data = res.data;
        if (this.oldMajor) {
          data.major = this.oldMajor;
        }
        this.status = data.status;
        this.formData = data;
        this.source = data.source;
        this.initForm();
        this.currentKeys = data.keys || "";
        this.currentOrg = data.deptManageName || "";
        this.currentEquipmentName = data.equipmentName || "";
        this.currentEquipment = data.equipmentId || "";
        this.orderTitle = data.title;
        this.$emit("setOrderTitle", data.title);
        if (
          data.title == data.deptManageName + data.equipmentName + data.keys ||
          [null, ""].includes(data.title)
        ) {
          //用户是否自定义了工单名
          this.$emit("initUserInput", false);
          if ([null, ""].includes(data.title)) {
            this.$message.warning("检测到工单标题为空，已为您自动生成标题！");
            this.orderTitle =
              data.deptManageName + data.equipmentName + data.keys;
            this.$emit("setOrderTitle", this.orderTitle);
          }
        } else {
          this.$emit("initUserInput", true);
        }
        //初始化发现人
        let {
          finder,
          finderName,
          finderType,
          equipmentName,
          equipmentId,
          keys,
          keysId,
        } = data;
        let option = this.$utils.getOptionData(finderName, finder, finderType);
        //let keyOption = this.$utils.getOptionData(keys, keysId);
        let equipmentOption = this.$utils.getOptionData(
          equipmentName,
          equipmentId
        );
        /* 缺陷关键字 */
        //data.keyArr = keysId;
        /* 设备 */
        data.finderNameArr = finder;
        data.equipmentArr = equipmentId;
        setTimeout(() => {
          //避免跟initForm里面对this.basicConfig.itemArr处理的冲突
          if (this.$refs.basicForm) {
            this.$refs.basicForm.setItemOption("finderName", option);
            this.$refs.basicForm.setItemOption(
              "equipmentName",
              equipmentOption
            );
            //this.$refs.basicForm.setItemOption("keys", keyOption);
          }
        }, 200);
        this.$emit("changeFormData", data);
        //初始化附件ID
        this.attachSetting.businessId = data.id;
        if (data.equipmentId != "" && data.origin != "eam.1.0") {
          this.initModel(data.equipmentId);
        }
      });
    },
    getFormData(isCheck) {
      return this.$refs.basicForm.getFormData(isCheck);
    },
    //选择关键字
    selectKeys(data) {
      let { keyword, id, others } = data;
      let formData = this.$refs.basicForm.getCurrentData();
      this.$refs.basicForm.setFormItem("keys", keyword);
      this.currentKeys = keyword;
      this.$refs.basicForm.setFormItem("keysId", id);
      if (formData.desc == "") {
        this.$refs.basicForm.setFormItem("desc", others);
      }
    },
    getTitle() {
      return this.orderTitle;
    },
    setAttachId(id, type) {
      new Promise((resolve, reject) => {
        this.attachSetting = {
          businessId: id,
          businessType: "base",
        };
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachFile.doSubmitFiles(type);
      });
    },
    uploadSuccess() {
      let obj = JSON.parse(JSON.stringify(this.$router.currentRoute.query));
      obj = Object.assign(obj, {
        id: this.attachSetting.businessId,
        pageType: "edit",
      });
      this.$router.push({
        query: obj,
      });
    },
    haveAttachFile() {
      let hasFile = this.$refs.attachFile.getFileListData();
      return hasFile.length > 0;
    },
    saveAttachFile() {
      this.$refs.attachFile.save();
    },
    selectPatrol(){
      this.$emit("openSelectPatrol");
    },
    //初始化
    async initModel(id) {
      let res = await getEquipment(id);
      this.$emit("setTypeId", res.data.typeId)
      this.$refs.basicForm.setFormItem("equipmentCode", res.data.code);
      res.data.basicParams.forEach((item) => {
        if (item.paramCode == "company") {
          this.$refs.basicForm.setFormItem(
            "manufacturer",
            item.paramValue || ""
          );
        } else if (item.paramName == "型号") {
          this.$refs.basicForm.setFormItem("model", item.paramValue || "");
        } else if (item.paramCode == "location") {
          this.$refs.basicForm.setFormItem(
            "equipmentLocation",
            item.paramValue || ""
          );
          let locationObj = {
            locationName: item.paramValue,
            location: item.paramResult,
          };
          this.$emit("setLocation", locationObj);
        }
      });
      
    },
    //设备带出设备管理单位以及专业
    async setDeptManage(form) {
      let res = await getEquipment(form.equipmentId);
      this.$emit("setTypeId", form.typeId)
      res.data.basicParams.forEach((item) => {
        if (item.paramCode == "deptId") {
          if (!item.paramValue) {
            this.$message.warning(
              "该设备没有设备管理单位，请选择有设备管理单位的设备！"
            );
            this.currentOrg = "";
            this.$refs.basicForm.setFormItem("deptManageName", "");
            this.$refs.basicForm.setFormItem("deptManage", "");
          } else {
            this.currentOrg = item.paramValue;
            this.$refs.basicForm.setFormItem("deptManageName", item.paramValue);
            this.$refs.basicForm.setFormItem("deptManage", item.paramResult);
          }
        } else if (item.paramCode == "major") {
          if (item.paramValue) {
            this.$refs.basicForm.setFormItem("major", item.paramResult);
          } else {
            this.$refs.basicForm.setFormItem("major", "");
          }
        } else if (item.paramCode == "company") {
          this.$refs.basicForm.setFormItem(
            "manufacturer",
            item.paramValue || ""
          );
        } else if (item.paramName == "型号") {
          this.$refs.basicForm.setFormItem("model", item.paramValue || "");
        }
      });
    },
    goDetailPage(row) {
      const { href } = this.$router.resolve({
        name: "parameterInfor",
        query: {
          equipId: row.equipmentId,
        },
      });
      window.open(href, "_blank");
    },
    goToPatrolRobot(id) {
      const href = `http://ips.gdhwater.com:8091/#/faultDetail?faultId=${id}`;
      window.open(href, "_blank");
    },
  },
};
</script>
<style lang="less" scoped>
.attachConten {
  display: flex;
  flex-flow: wrap nowrap;
  .redPoint {
    color: red;
  }
  .attachTitle {
    width: 120px;
  }
  .tebleDiv {
    width: 100%;
  }
}
.dayInput {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .link {
    //width: 60px;
    height: 32px;
    margin-left: 10px;
    margin-bottom: 2px;
  }
}
</style>
